package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyJuYiDai;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeJuYiDai;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 安心分期（出）&桔易贷 半28
 * 链接：https://ycncwx7jq9fw.feishu.cn/docx/AiWndBfRMoDl16xCdJJc3GGpnwg
 * 密码：6792G&66
 *
 * @author gwc
 * @create 2025-07-29 上午10:25
 */
@ApiPlan(productId = "381", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatJuYiDaiPhoneMd5ConvertV2 implements ApiPlatformPhoneMd5ConvertHandler {

    private static final String KEY = "42h503C7CaIJ3D7U";
    private static final String CHANNEL = "nsPdQTP8";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        //  撞库实体类
        ApiPlatDataExchangeJuYiDai juYiDaiData = new ApiPlatDataExchangeJuYiDai();
        //  拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        //  手机号 MD5
        juYiDaiData.setPhoneMd5(apiDataExchangeParameter.getPhoneMd5());
        //  用户姓名，无则默认 "默认姓名"
        juYiDaiData.setRealName("默认姓名");
        //   年龄（20-55 岁）
        juYiDaiData.setAge(apiFieldConverter.getAgeInt());
        //  性别（1：男，0：女）
        Integer sex = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "0", 1)
                .when(apiDataExchangeParameter.getSex(), "1", 0)
                .end(1);
        juYiDaiData.setSex(sex);
        //  所在城市（如：成都市）
        juYiDaiData.setCity(apiDataExchangeParameter.getCity());
        //  城市编码
        juYiDaiData.setCityCode(apiDataExchangeParameter.getAreaCode());
        //  芝麻分：1：无芝麻分，2：600分以下，3：600~650分，4：650~700分，5：700分以上
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 3)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 4)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 5)
                .end(1);
        juYiDaiData.setSesameScore(zhima);
        //  公积金：1：无，2：有
        Integer providentFund = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 2)
                .end(1);
        juYiDaiData.setFund(providentFund);
        //  社保：1：无，2：6个月以下，3：6个月以上
        Integer socialSecurity = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 3)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 2)
                .end(1);
        juYiDaiData.setSocial(socialSecurity);
        //  保单情况：1：无，2：有
        Integer baodanIs = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 2)
                .end(1);
        juYiDaiData.setInsurance(baodanIs);
        //  房产情况：1：无，2：有
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 2)
                .end(1);
        juYiDaiData.setHouse(house);
        //  名下车产：1：无，2：有
        Integer vehicle = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 2)
                .end(1);
        juYiDaiData.setCar(vehicle);
        //  职业身份：1：上班族，2：公务员/事业单位，3：私营业主，4：个体户，5：其他
        Integer career = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 1)
                .when(apiDataExchangeParameter.getCareer(), "2", 5)
                .when(apiDataExchangeParameter.getCareer(), "3", 3)
                .when(apiDataExchangeParameter.getCareer(), "4", 2)
                .when(apiDataExchangeParameter.getCareer(), "5", 4)
                .end(1);
        juYiDaiData.setProfession(career);
        //  借款金额（单位：元，默认10000）
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 30000)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 50000)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 100000)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 200000)
                .end(10000);
        juYiDaiData.setLoanAmount(money);
        //  用户 IP（无则默认 127.0.0.1）
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getIp())) {
            juYiDaiData.setIp(apiDataExchangeParameter.getIp());
        } else {
            juYiDaiData.setIp("127.0.0.1");
        }
        //  用户客户端（1：Android，2：iOS，默认1）
        juYiDaiData.setClient(1);
        //  月收入（单位：元，默认4000）
        Integer monthlySalary = ChooseEq.create()
                .when(apiDataExchangeParameter.getMonthlySalary(), "1", 2000)
                .when(apiDataExchangeParameter.getMonthlySalary(), "2", 5000)
                .when(apiDataExchangeParameter.getMonthlySalary(), "3", 8000)
                .when(apiDataExchangeParameter.getMonthlySalary(), "4", 15000)
                .when(apiDataExchangeParameter.getMonthlySalary(), "5", 30000)
                .end(4000);
        juYiDaiData.setMonthlyIncome(monthlySalary);
        //  加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(juYiDaiData));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel", CHANNEL);
            newMap.put("data", data);
            newMap.put("requestNo", apiDataExchangeParameter.getReqId());
        });
        return map;
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if(!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONObject resData = jsonObject.getJSONObject("data");
        //  分润前价格
        BigDecimal price = resData.getBigDecimal("price");
        //  订单号
        String orderId = resData.getString("orderId");
        //  授权地址
        String url = resData.getString("url");
        //  产品logo
        String logo = resData.getString("logo");
        String companyName = resData.getString("companyName");
        String productName = resData.getString("productName");
        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();

        result.setPrice(price);
        result.setLogoPath(logo);
        result.setApplyId(orderId);
        result.setCallUrl(url);
        result.setDisplayName(companyName);
        result.setProductName(productName);
        return result;
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        //  进件实体类
        ApiPlatApplyJuYiDai juYiDaiData = new ApiPlatApplyJuYiDai();
        //  拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        //  手机号明文
        juYiDaiData.setPhone(apiApplyParameter.getPhone());
        //  用户姓名
        juYiDaiData.setRealName(apiApplyParameter.getUserName());
        //   年龄（20-55 岁）
        juYiDaiData.setAge(apiFieldConverter.getAgeInt());
        //  性别（1：男，0：女）
        Integer sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "0", 1)
                .when(apiApplyParameter.getSex(), "1", 0)
                .end(1);
        juYiDaiData.setSex(sex);
        //  所在城市（如：成都市）
        juYiDaiData.setCity(apiApplyParameter.getCity());
        //  城市编码
        juYiDaiData.setCityCode(apiApplyParameter.getAreaCode());
        //  芝麻分：1：无芝麻分，2：600分以下，3：600~650分，4：650~700分，5：700分以上
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 2)
                .when(apiApplyParameter.getSesameCredit(), "2", 3)
                .when(apiApplyParameter.getSesameCredit(), "3", 4)
                .when(apiApplyParameter.getSesameCredit(), "4", 5)
                .end(1);
        juYiDaiData.setSesameScore(zhima);
        //  公积金：1：无，2：有
        Integer providentFund = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 1)
                .when(apiApplyParameter.getProvidentFund(), "2", 2)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 2)
                .end(1);
        juYiDaiData.setFund(providentFund);
        //  社保：1：无，2：6个月以下，3：6个月以上
        Integer socialSecurity = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 1)
                .when(apiApplyParameter.getSocialSecurity(), "2", 2)
                .when(apiApplyParameter.getSocialSecurity(), "3", 3)
                .when(apiApplyParameter.getSocialSecurity(), "4", 2)
                .end(1);
        juYiDaiData.setSocial(socialSecurity);
        //  保单情况：1：无，2：有
        Integer baodanIs = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 2)
                .end(1);
        juYiDaiData.setInsurance(baodanIs);
        //  房产情况：1：无，2：有
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 2)
                .end(1);
        juYiDaiData.setHouse(house);
        //  名下车产：1：无，2：有
        Integer vehicle = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 1)
                .when(apiApplyParameter.getCarInfo(), "2", 2)
                .when(apiApplyParameter.getCarInfo(), "3", 2)
                .when(apiApplyParameter.getCarInfo(), "4", 2)
                .end(1);
        juYiDaiData.setCar(vehicle);
        //  职业身份：1：上班族，2：公务员/事业单位，3：私营业主，4：个体户，5：其他
        Integer career = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 1)
                .when(apiApplyParameter.getCareer(), "2", 5)
                .when(apiApplyParameter.getCareer(), "3", 3)
                .when(apiApplyParameter.getCareer(), "4", 2)
                .when(apiApplyParameter.getCareer(), "5", 4)
                .end(1);
        juYiDaiData.setProfession(career);
        //  借款金额（单位：元，默认10000）
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 30000)
                .when(apiApplyParameter.getLoanAmount(), "2", 50000)
                .when(apiApplyParameter.getLoanAmount(), "3", 100000)
                .when(apiApplyParameter.getLoanAmount(), "4", 200000)
                .end(10000);
        juYiDaiData.setLoanAmount(money);
        //  用户 IP（无则默认 127.0.0.1）
        if (ValidParam.isNotEmpty(apiApplyParameter.getIp())) {
            juYiDaiData.setIp(apiApplyParameter.getIp());
        } else {
            juYiDaiData.setIp("127.0.0.1");
        }
        //  撞库返回的订单号
        juYiDaiData.setOrderId(apiApplyParameter.dataExchangeApplyId());
        //  用户授权协议地址
        juYiDaiData.setProtocolUrl(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
        //  用户客户端（1：Android，2：iOS，默认1）
        juYiDaiData.setClient(1);
        //  月收入（单位：元，默认4000）
        Integer monthlySalary = ChooseEq.create()
                .when(apiApplyParameter.getMonthlySalary(), "1", 2000)
                .when(apiApplyParameter.getMonthlySalary(), "2", 5000)
                .when(apiApplyParameter.getMonthlySalary(), "3", 8000)
                .when(apiApplyParameter.getMonthlySalary(), "4", 15000)
                .when(apiApplyParameter.getMonthlySalary(), "5", 30000)
                .end(4000);
        juYiDaiData.setMonthlyIncome(monthlySalary);
        //  加密数据
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(juYiDaiData));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel", CHANNEL);
            newMap.put("data", data);
            newMap.put("requestNo", apiApplyParameter.getReqId());
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        JSONObject jsonObject = JsonUtils.get(requestVO.getBody());
        String orgId = jsonObject.getString("orderId");
        String phoneMd5 = jsonObject.getString("phoneMd5");

        RespPlatformNoticeApply applyNotice = new RespPlatformNoticeApply();
        applyNotice.setApplyId(orgId);
        applyNotice.setPhoneMd5(phoneMd5);
        return applyNotice;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {

        boolean b = apiBizStatus.hasBizSuc();

        if (b) {
            return MapUtils.newHashMap(newHashMap -> {
                newHashMap.put("code", 200);
                newHashMap.put("msg", "操作成功");
            });
        }
        return MapUtils.newHashMap(newHashMap -> {
            newHashMap.put("code", 500);
            newHashMap.put("msg", "操作失败");
        });
    }
}
